package com.zhupanlin.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.zhupanlin.io.Resources;
import com.zhupanlin.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 描述信息：
 *
 * @author zhupanlin
 * @version 1.0
 * @date 2025/2/8 17:18
 */
public class XMLConfigBuilder {
    
    private Configuration configuration;
    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 该方法使用 dom4j 解析配置文件，封装Configuration对象并返回
     * @param is
     * @return
     */
    public Configuration parseConfig(InputStream is) throws DocumentException, PropertyVetoException {

        Document document = new SAXReader().read(is);
        // 获取根节点
        Element rootElement = document.getRootElement();
        List<Element> propertyList = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        propertyList.forEach(element -> {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        });

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        
        configuration.setDataSource(comboPooledDataSource);
        
        // mapper.xml 解析：拿到路径 -> 拿到文件流 -> dom4j 解析 -> 封装到 Configuration 中
        List<Element> mappers = rootElement.selectNodes("//mapper");

        for (Element element : mappers) {
            String mapperPath = element.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }

        return configuration;
    }
    
}